<template>
  <div class='operate'>
    <!-- <ActionBar 
      :span='operateTypeObj.toggleStateTxt' 
      @spanEvent='toggleState()'
      :visible="operateTypeObj.operateType === 'add' ? false : true" /> -->
    <div class='scrollView'>
      <template v-for="(item, index) in unitMembersArr" wx:key='index'>
        <field
          :key='index'
          v-if="item['type'] === 'field' || item['type'] === 'field_phone'"
          v-model="item['value']"
          clearable
          :maxLength="item['maxLength']"
          :required="item['required']"
          :readonly="item['readonly']"
          :label="item['label']"
          :placeholder="'请输入' + item['label']"
        />
        <div 
          :key='index' 
          v-else-if="item['type'] === 'selector' && item['visible']"
          class='container'>
          <span :class="item['required'] ? 'required_formItem' : ''">
            {{item.label ? item.label : ''}}
          </span>
					<picker
						mode='selector'
						:range="pikerList[item.key]"
						range-key='text'
						:value="index"
						@change="getSelectedItem($event, index, item.key)">
						<span class='container_right'>
							<span v-if='item.value.text'>{{item.value.text}}</span>
							<span v-else class='placeholder'>请选择</span>
							<image v-if='!item.readonly' class='arrow' src='/static/images/home/_unitPersonnelManaage/right.png'/>
						</span>
					</picker>
        </div>
        <div 
          :key='index'
          v-else-if="item['type'] === 'switch' && operateTypeObj.operateType !== 'add'"
          @change='handleSwitch'
          class='container'>
          <span :class="item['required'] ? 'required_formItem' : ''">
            {{item['label']}}
          </span>
          <span v-if="operateTypeObj.editable">
            <switch :checked="item['value'] == '0'" size='15px' @change="handleSwitch($event, index)"/>
          </span>
          <span v-else>{{item['value'] == '0' ? '在用' : '停用'}}</span>
        </div>
        <div 
          :key='index'
          v-else-if="item['type'] === 'title'"
          class='container'>
          <span>{{item['label']}}</span>
          <span>{{item['value']}}</span>
        </div>
      </template>
    </div>
    <div class='operate_submit' v-if='operateTypeObj.editable' @click="submit">{{operateTypeObj.saveTxt}}</div>
  </div>
</template>

<script>
/**
 * 本单位人员管理查看、新增、修改组件
 */
import UnitMembersObj from './unitMembersObj.js'
import ActionBar from '@/common/components/actionBar'
import field from './field'

export default {
  components: {
    ActionBar, field
  },
  data () {
    return {
      operateTypeObj: {}, // 将查看、添加、删除影响的文本保存到这个对象
      unitMembers: {}, // 订货单位对象，根据该对象对表单项的各个属性以及提交校验进行维护
      visible: false, // 碳库是否可见
      pikerList: {
				ccbRoleId: [{
						id: 0,
						text: '管理员'
					},
					{
						id: 1,
						text: '店员'
					}],
				ccbDataAuthType: [
					{
						text: '全部',
						id: '0'
					},
					{
						text: '指定门店',
						id: '1',
						control: '5' // 被控制组件的索引
					}
				]
			}
    }
  },
  computed: {
    unitMembersArr: { // 为了保证表单项目的输出顺序所以最后转化为数组
      get: function () {
        return Array.from(this.unitMembers)
      },
      set: function (itemOBj) {
        this.unitMembers[itemOBj.index][itemOBj.key] = itemOBj.value
      }
    }
  },
  onLoad (option) {
		this.id = option.id
    this.operateTypeObj = this.OperateTypeObj(option.type)
  },
  methods: {
    OperateTypeObj (operateType = 'view') { // 操作类型和界面上的随类型变化的文本的映射类
      var _this = {}
      _this.operateType = operateType
      switch (operateType) {
        case 'view':
          _this.title = '本单位人员查看' // 标题
          _this.editable = false // 是否可编辑
          _this.toggleStateTxt = '编辑' // 操作按钮名称
          break
        case 'modify':
          _this.title = '本单位人员编辑'
          _this.editable = true
          _this.toggleStateTxt = '取消'
          _this.saveTxt = '保存'
          break
        case 'add':
          _this.title = '新增用户'
          _this.editable = true
          _this.toggleStateTxt = ''
          _this.saveTxt = '保存'
          break
        default:
          console.log('操作类型逻辑判断有误，请检查')
      }
      uni.setNavigationBarTitle({
        title: _this.title
      })
      if (operateType !== 'add') {
        this.getUserInfo(operateType, this.id)
      } else {
        this.unitMembers = new UnitMembersObj(operateType) // 改变状态后对
      }
      return _this
    },
    handleSwitch (e, index) { // 开关切换
      this.unitMembers[index].value = ~this.unitMembers[index].value + 2
    },
    toggleState () { // 编辑查看之间切换状态
      this.operateTypeObj = this.OperateTypeObj(this.operateTypeObj.toggleStateTxt === '编辑' ? 'modify' : 'view')
    },
    getSelectedItem (e, index, key) { // 选择框选中事件
			var item = this.pikerList[key].find(item => item.id == e.target.value)
			this.unitMembersArr[index].value = item
    },
    getUserInfo (operateType, id) {
      this.http.GET({
        name: 'userinfo',
        params: {
					userId: id
				}
      }).then(res => {
        var data = res.data
        this.unitMembers = new UnitMembersObj(this.operateTypeObj.operateType, res.data) // 改变状态后对
        this.admin = res.data.admin
      })
    },
    submit () { // 最终提交
      let formData = {} // 最终组合成的表单数据
			console.log(this.unitMembersArr)
			return
      for (var i = 0; i < this.unitMembersArr.length; i++) {
        let item = this.unitMembersArr[i]
        if (item.visible === false) {
          continue
        }
        if (typeof (item.value) === 'object') {
          if (item.required && (!item.value.id || item.value.id === '')) { // 对象必填校验
            console.log('必填项', item.label, '不能空')
            Toast({
              message: '必填项' + item.label + '不能空',
              position: 'bottom'
            })
            break
          }
          if (item.type !== 'title') {
            formData[item.key] = item.value.id
          }
        } else {
          if (item.required && item.value === '') { // 字符串必填校验
            console.log('必填项', item.label, '不能空')
            Toast({
              message: '必填项' + item.label + '不能空',
              position: 'bottom'
            })
            break
          }
          // if (item.required && item.type === 'field_phone') { // 手机号是必填项时进行格式校验
          //   var myreg = /^[1][3,4,5,7,8][0-9]{9}$/
          //   if (!(myreg.test(item.value))) {
          //     console.log('请输入有效的', item.label, '号码')
          //     Toast({
          //       message: '请输入有效的' + item.label + '号码',
          //       position: 'bottom'
          //     })
          //     break
          //   }
          // }
          if (item.type !== 'title') {
            formData[item.key] = item.value
          }
        }
      }
      if (i === this.unitMembersArr.length) {
        console.log('表单校验成功，即将提交。。。')
        console.log('formData', formData)
        this.http.POST({
          name: 'user_add',
          params: formData
        }).then(res => {
          // this.go({name: 'mine_unitMembers'})
          if (res.status === 0) {
            this.back(1)
          }
        })
      }
    }
  }
}
</script>

<style scoped>
  .required_formItem:before{
    content: '*';
    color: #FA4943;
  }
  .operate {
    width: 750rpx;
    height: 100vh;
    font-size: 28rpx;
    position: relative;
    border-top: 1rpx solid #ebedf0;
  }
  .scrollView {
    background: #FFFFFF;
    width: 100%;
    height: 100vh;
    overflow-x: hidden;
  }
  .scrollView::-webkit-scrollbar {
    display: none;
  }
  .operate_submit {
    position: fixed;
    bottom: 0rpx;
    width: 100%;
    padding: 20rpx;
    text-align: center;
    z-index: 10;
    background: #FA4943;
    color: #FFFFFF;
  }
  .arrow {
    width: 30rpx;
    height: 30rpx;
    margin-left: 10rpx;
  }
  .container {
    width: 100%;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid #ebedf0;
    box-sizing: border-box;
    padding: 20rpx 40rpx 20rpx 10rpx;
    margin-left: 20rpx;
    text-align: right;
    height:auto;
    flex-direction:row;
  }
  .container_right {
    display: flex;
    align-items: center;
  }
  .placeholder {
    color: #999999
  }
	switch {
		transform: scale(0.5);
		margin-right: -35upx;
	}
</style>

